package com.wcs.exam.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.wcs.exam.common.enums.ExamStatusEnum;
import com.wcs.exam.controller.biz.ExamCommonBiz;
import com.wcs.exam.dao.ExamUserRecordDao;
import com.wcs.exam.dao.impl.mapper.entity.ExamUserRecord;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@RequiredArgsConstructor
@Component
public class ExamJob {

    @NotNull
    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @NotNull
    private final ExamCommonBiz examCommonBiz;

    @NotNull
    private final ExamUserRecordDao examUserRecordDao;

    /**
     * 考试-超时关闭（单位：毫秒，1秒=1000毫秒）
     */
    @Scheduled(fixedRate = 5000)
    public void TimeoutSubmitTask() {
        LambdaQueryWrapper<ExamUserRecord> wrapper = new LambdaQueryWrapper<ExamUserRecord>()
                .eq(ExamUserRecord::getExamStatus, ExamStatusEnum.NOT_OVER.getCode())
                // 查询考试结束时间小于当前时间前20秒的考试记录，减去20s为了防止和前端定时任务处理冲突
                .le(ExamUserRecord::getEndTime, LocalDateTime.now().minusSeconds(20));

        int pageCurrent = 1;
        int pageSize = 1000;
        boolean isContinue;
        do {
            log.info("【考试超时交卷】处理开始");
            IPage<ExamUserRecord> page = examUserRecordDao.page(PageDTO.of(pageCurrent, pageSize), wrapper);
            if (ObjectUtil.isNull(page) || CollectionUtil.isEmpty(page.getRecords())) {
                return;
            }

            // 处理考试记录
            for (ExamUserRecord record : page.getRecords()) {
                log.info("考试记录ID：{}-用户ID：{}-考试类型：{}-考试ID：{}-试卷ID：{}，超时交卷处理", record.getId(), record.getUserId(), record.getExamType(), record.getRelateId(), record.getPaperId());
                threadPoolTaskExecutor.execute(() -> examCommonBiz.handleFinishExam(record));
            }

            // 判断是否继续
            pageCurrent++;
            isContinue = page.getCurrent() < page.getPages();
        } while (isContinue);

        log.info("【考试超时交卷】处理完成");
    }

}
